import flask
import openai as openai
from flask import Flask, request

# app = Flask(__name__)

from flask_cors import CORS
app = Flask(__name__)
CORS(app)

openai.api_key='请输入您自己的key'
openai.proxy = "127.0.0.1:7890"  # 科学上网代理地址


@app.route('/')
def hello_world():  # put application's code here
    return 'Hello World!'

#你开发了一个登录接口  login
#参数 url 普通参数 http://127.0.0.1:5000/login?name=zhangsan&pwd=123  request.args  字典
# 请求协议 get  post
# 请求参数json格式
@app.route('/login',methods=['GET','POST'])
def logintest():
    print(request)
    if request.is_json:
        print(request.json.get('name'))
        print(request.json.get('pwd'))
    else:
      print(request.args.get("name"))
      print(request.args.get("pwd"))
    return 'Hello World login'


@app.route('/chat',methods=['POST'])
def chat():
    if request.is_json:
        temperature = request.json.get('temperature',0.5)
        max_tokens = request.json.get('max_tokens',3000)
        content = request.json.get('content', "")
        if len(content)==0:
            return '没有请求内容'
        print('请求内容',content)
        result = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            temperature=float(temperature),
            max_tokens=int(max_tokens),  # 4097
            messages=[
                {"role": "user", "content": f"{content}"}
            ]
        )
        return_result = result['choices'][0]['message']['content']
        print(return_result)
        return return_result
    return '参数不满足要求'

#支持stream
@app.route('/chat2',methods=['GET','POST'])
def chat2():  # put application's code here
    if request.is_json:
        content = request.json.get("content", "")
        temperature = request.json.get("temperature", "0.5")
        max_tokens = request.json.get("max_tokens", "3000")
    else:
      #  data = request.args.get("data")
        content  = request.args.get("content", "")
        temperature = request.args.get("temperature", "0.5")
        max_tokens = request.args.get("max_tokens", "3000")
    print(content)
    def stream():
       try:
        result = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            temperature=float(temperature),
            max_tokens=int(max_tokens),
            messages=[
                {"role": "user", "content": content}
            ],
            stream=True
        )
       except Exception as e:
          print(e)
       for line in result:
        if line["choices"][0]["finish_reason"] is not None:
          data = '[DONE]'
        else:
          data = line["choices"][0]["delta"].get("content", "")
        yield 'data: %s\n\n' % data.replace("\n", "<br/>")
    return flask.Response(stream(), mimetype='text/event-stream')

@app.route('/user/<username>',methods=['POST'])
def show_user_profile(username):
     return '路径参数'

if __name__ == '__main__':
    app.run()
